package com.company.site.wechat;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.company.base.common.WeChatConstant;
import com.company.base.utils.CheckUtil;
import com.company.base.utils.DateUtil;
import com.company.base.utils.MessageUtil;
import com.company.core.utils.IpUtil;
import com.company.site.mode.reqMessage.ReqImageMessage;
import com.company.site.mode.reqMessage.ReqLinkMessage;
import com.company.site.mode.reqMessage.ReqLocationMessage;
import com.company.site.mode.reqMessage.ReqTextMessage;
import com.company.site.mode.reqMessage.ReqVideoMessage;
import com.company.site.mode.reqMessage.ReqVoiceMessage;
import com.company.site.mode.resMessage.Article;
import com.company.site.mode.resMessage.NewsMessage;
import com.company.site.mode.resMessage.ResBaseMessage;
import com.company.site.mode.resMessage.ResTextMessage;
import com.company.site.mode.wechatuser.WechatUser;
import com.company.site.user.UserService;

/**
 * 微信消息处理核心类
 * @author Jeremy.Tan
 *
 */
@Service
public class WeChatService {

	@Resource
	WeChatMapper weChatMapper;
	@Resource
	UserService userService;

	/**
	 * 处理用户发送的各种类型消息
	 * 
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public String processRequest(HttpServletRequest request) throws Exception {
		String respMessageStr=null;                                       
		ResBaseMessage resMessage = new ResBaseMessage();
		Map<String, String> requestMap = MessageUtil.parseXml(request);
		String ip = IpUtil.getIp(request);
		String openID=requestMap.get("FromUserName"); 
		try {
			switch(requestMap.get("MsgType")){
				// 处理用户发送的文本消息
				case WeChatConstant.REQ_MESSAGE_TYPE_TEXT:
					resMessage=processTxtMsg(requestMap,ip);
					break;
						
				// 处理用户发送的图片消息
				case WeChatConstant.REQ_MESSAGE_TYPE_IMAGE:break;
				
				// 处理用户语音文件
				case WeChatConstant.REQ_MESSAGE_TYPE_VOICE:break;
				
				// 处理视频文件
				case WeChatConstant.REQ_MESSAGE_TYPE_VIDEO:break;
				
				// 处理用户发送的地理信息
				case WeChatConstant.REQ_MESSAGE_TYPE_LOCATION:break;
				
				// 链接消息
				case WeChatConstant.REQ_MESSAGE_TYPE_LINK:break;
				
				// 接收事件推送
				case WeChatConstant.REQ_MESSAGE_TYPE_EVENT:
					resMessage=proceeEventMsg(requestMap,resMessage,ip,request);
					break;
				
				default:break;
			}
			
			// 回复的是文本消息
			if(resMessage instanceof ResTextMessage){
				respMessageStr = MessageUtil.textMessageToXml((ResTextMessage)resMessage);
			}
			
			// 回复的是图文链接消息
			if(resMessage instanceof NewsMessage){
				respMessageStr =MessageUtil.newsMessageToXml((NewsMessage)resMessage);
			}
			
			// 保存用户发送的不同类型的消息
			saveReqMessage(requestMap);
		} catch (Exception e) {
			e.printStackTrace();
			respMessageStr=null;
		} finally {
			requestMap = null;
		}
		System.out.println("返回消息消息："+respMessageStr);
		return respMessageStr;
	}

	/**
	 * 处理用户文字消息
	 * @param respMessage
	 * @param requestMap
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private ResBaseMessage processTxtMsg(Map<String, String> requestMap,String ip) throws UnsupportedEncodingException {
	    boolean hasResponse=false;                            // 判定是否有匹配的回复内容
		String msgContent = requestMap.get("Content");        // 用户发送的内容
		String openID=requestMap.get("FromUserName");         // 用户openID
		String fromUserName=requestMap.get("ToUserName");
		String msgId = requestMap.get("MsgId");  
		ResBaseMessage responseMsg=new ResBaseMessage();
		System.out.println(msgContent);
		System.out.println(openID);
		System.out.println(fromUserName);
		System.out.println(msgId);
		

		//投票
		if (msgContent.contains("答题")) {
			System.out.println(hasResponse);
			ResTextMessage textMessage = new ResTextMessage();
			textMessage.setToUserName(openID);
			textMessage.setFromUserName(fromUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setFuncFlag(0);
			textMessage.setContent(WeChatConstant.RETURN_ACTURL);
			textMessage.setMsgType(WeChatConstant.RESP_MESSAGE_TYPE_TEXT);
			hasResponse=true;
			responseMsg=textMessage;
		};
//		// 收到的用户消息为空
//		if(!CheckUtil.isEmpty(msgContent)){
//			msgContent=msgContent.trim();
//		}
//		
//		// 如果没有匹配到指令
//		if(!hasResponse){
//			System.out.println(hasResponse);
//			ResTextMessage textMessage = new ResTextMessage();
//			textMessage.setToUserName(openID);
//			textMessage.setFromUserName(fromUserName);
//			textMessage.setCreateTime(new Date().getTime());
//			textMessage.setFuncFlag(0);
//			textMessage.setContent(WeChatConstant.RETURN_MSG_SUBSCRIBE);
//			textMessage.setMsgType(WeChatConstant.RESP_MESSAGE_TYPE_TEXT);
//			hasResponse=true;
//			responseMsg=textMessage;
//		}
		System.out.println(responseMsg);
		return responseMsg;
	}

	/**
	 * 处理用户所有推送事件
	 * @param requestMap 所有消息信息
	 * @param eventType  推送事件类型  1.关注事件 2.取消关注事件 3.扫描带参数二维码事件 4.自定义菜单事件 5.上报地理位置事件
	 * @param resMessage 回复消息
	 * @throws UnsupportedEncodingException 
	 */
	public ResBaseMessage proceeEventMsg(Map<String, String> requestMap,ResBaseMessage resMessage,String ip,HttpServletRequest request) throws UnsupportedEncodingException{
		
		// 推送事件类型  1.关注事件 2.取消关注事件 3.扫描带参数二维码事件 4.自定义菜单事件 5.上报地理位置事件
		switch(requestMap.get("Event")){
			// 关注事件
			case WeChatConstant.EVENT_TYPE_SUBSCRIBE:
				resMessage = processSubscribe(requestMap,resMessage,request);
				break;
			
			// 取消关注事件
			case WeChatConstant.EVENT_TYPE_UNSUBSCRIBE:
				resMessage = processUnSubscribe(requestMap,resMessage,request);
				break;
				
			// 扫描带参数二维码事件
			case WeChatConstant.REQ_MESSAGE_TYPE_SCAN:break;
			
			// 自定义菜单事件
			case WeChatConstant.EVENT_TYPE_CLICK:
				resMessage = processMenuClick(requestMap,ip);
				break;
			
			// 上报地理位置事件
			case WeChatConstant.EVENT_TYPE_LOCATION:break;
			
			// 点击菜单跳转链接时的事件推送 
			case WeChatConstant.EVENT_TYPE_VIEW:break;
			
			// 扫码推事件且弹出“消息接收中”提示框
		    case WeChatConstant.EVENT_TYPE_SCANCODE_WAITIMSG:
		    					resMessage = processScanCode(requestMap);	
		    					break;
			default:break;
		}
		return resMessage;
	}
	
	public static void main(String[] args){
		System.out.println(DateUtil.stringToDate("2015-4-20 15:01:08"));
		System.out.println( DateUtil.stringToDate("2015/4/20 15:17:37"));
		System.out.println(DateUtil.diffMinute(DateUtil.stringToDate("2015-4-20 15:01:08")
				, DateUtil.stringToDate("2015-4-20 15:17:37")));
	}
	
	
	private  ResBaseMessage processScanCode(Map<String, String> requestMap) throws UnsupportedEncodingException{
		String returnMsg=null;
		String sr=requestMap.get("ScanResult");
		String openid=requestMap.get("FromUserName");
		String eventKey=requestMap.get("EventKey");
		WechatUser user=userService.getUserInfoByOpenid(openid);
//		if(CheckUtil.isEmpty(user)){
//			userService.subscribeUser(openid);
//			user=userService.getUserInfoByOpenid(openid);
//		}
		ResTextMessage textMessage = new ResTextMessage();
		textMessage.setToUserName(openid);
		textMessage.setFromUserName(requestMap.get("ToUserName"));
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setFuncFlag(0);
		textMessage.setContent(returnMsg);
		textMessage.setMsgType(WeChatConstant.RESP_MESSAGE_TYPE_TEXT);
		return textMessage;
	}
	
	/**
	 * 用户订阅公众号事件
	 * @param requestMap
	 * @param resMessage
	 * @throws UnsupportedEncodingException 
	 */
	private ResBaseMessage processSubscribe(Map<String, String> requestMap,ResBaseMessage resMessage,HttpServletRequest request) throws UnsupportedEncodingException{
		ResTextMessage textMessage = new ResTextMessage();
		textMessage.setToUserName(requestMap.get("FromUserName"));
		textMessage.setFromUserName(requestMap.get("ToUserName"));
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setFuncFlag(0);
		textMessage.setContent(WeChatConstant.RETURN_MSG_SUBSCRIBE);
		textMessage.setMsgType(WeChatConstant.RESP_MESSAGE_TYPE_TEXT);
		// 获取用户的微信基本资料
		userService.subscribeUser(requestMap.get("FromUserName"),request);
		System.out.println("用户关注公众号");
		return textMessage;
	}
	
	/**
	 * 用户取消关注公众号事件
	 * @param requestMap
	 * @param resMessage
	 * @throws UnsupportedEncodingException 
	 */
	private ResBaseMessage processUnSubscribe(Map<String, String> requestMap,ResBaseMessage resMessage,HttpServletRequest request) throws UnsupportedEncodingException{
		ResTextMessage textMessage = new ResTextMessage();
		textMessage.setToUserName(requestMap.get("FromUserName"));
		textMessage.setFromUserName(requestMap.get("ToUserName"));
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setFuncFlag(0);
		textMessage.setContent(WeChatConstant.RETURN_MSG_UNSUBSCRIBE);
		textMessage.setMsgType(WeChatConstant.RESP_MESSAGE_TYPE_TEXT);
		resMessage=textMessage;	
		// 取消关注后，解除绑定关系
		userService.unsubscribeUser(requestMap.get("FromUserName"),request);
		return textMessage;
	}
	
	/**
	 * 保存用户发送的不同类型的消息（文本消息 | 图片消息 | 语音消息 | 视频消息 | 地理位置消息 | 链接消息）
	 * 
	 * @param fromUserName
	 * @param toUserName
	 * @param msgType
	 * @param msgCreateTime
	 * @param msgId
	 * @param requestMap
	 */
	public void saveReqMessage(Map<String, String> requestMap) {
		String fromUserName = requestMap.get("FromUserName");         // get user open_id
		String toUserName =  requestMap.get("ToUserName");            // 微信帐号序列号
		String msgCreateTime = requestMap.get("CreateTime");          // 消息创建时间 （整型）
		String msgId = requestMap.get("MsgId");                       // 消息id，64位整型
		String msgType = requestMap.get("MsgType");                   // 消息回复类型
		
		switch (msgType) {
			// 1:文本消息
			case WeChatConstant.REQ_MESSAGE_TYPE_TEXT:
				String msgContent = requestMap.get("Content");
				ReqTextMessage reqTxtMessage = new ReqTextMessage();
				reqTxtMessage.setCreateTime(Long.valueOf(msgCreateTime));
				reqTxtMessage.setMsgId(Long.valueOf(msgId));
				reqTxtMessage.setMsgType(msgType);
				reqTxtMessage.setFromUserName(fromUserName);
				reqTxtMessage.setToUserName(toUserName);
				reqTxtMessage.setContent(msgContent);
				reqTxtMessage.setCreateTime(Long.valueOf(msgCreateTime));
				//weChatMapper.saveReqTextMessage(reqTxtMessage);
				break;
	
			// 图片消息
			case  WeChatConstant.REQ_MESSAGE_TYPE_IMAGE:
				String PicUrl = requestMap.get("PicUrl"); // 图片链接
				String MediaId = requestMap.get("MediaId"); // 图片消息媒体id，可以调用多媒体文件下载接口拉取数据。
				ReqImageMessage reqImgMsg = new ReqImageMessage();
				reqImgMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqImgMsg.setMsgId(Long.valueOf(msgId));
				reqImgMsg.setMsgType(msgType);
				reqImgMsg.setFromUserName(fromUserName);
				reqImgMsg.setToUserName(toUserName);
				reqImgMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqImgMsg.setPicUrl(PicUrl);
				reqImgMsg.setMediaId(MediaId);
				//weChatMapper.saveReqImgMsg(reqImgMsg);
				break;
	
			// 3:语音消息
			case WeChatConstant.REQ_MESSAGE_TYPE_VOICE:
				String vMediaId = requestMap.get("MediaId"); // 语音消息媒体id，可以调用多媒体文件下载接口拉取数据。
				String Format = requestMap.get("Format"); // 语音格式，如amr，speex等
				// String Recognition=requestMap.get("Recognition");
				// System.out.println("语音识别结果："+requestMap.get("Recognition").toString());
				ReqVoiceMessage reqVoiMsg = new ReqVoiceMessage();
				reqVoiMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqVoiMsg.setMsgId(Long.valueOf(msgId));
				reqVoiMsg.setMsgType(msgType);
				reqVoiMsg.setFromUserName(fromUserName);
				reqVoiMsg.setToUserName(toUserName);
				reqVoiMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqVoiMsg.setFormat(Format);
				reqVoiMsg.setMediaId(vMediaId);
				// reqVoiMsg.setRecognition(Recognition);
				//weChatMapper.saveReqVoiceMsg(reqVoiMsg);
				break;
	
			// 4:视频消息
			case WeChatConstant.REQ_MESSAGE_TYPE_VIDEO:
				String videoMediaId = requestMap.get("MediaId"); // 视频消息媒体id，可以调用多媒体文件下载接口拉取数据。
				String ThumbMediaId = requestMap.get("ThumbMediaId"); // 视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据。
				ReqVideoMessage reqVideoMsg = new ReqVideoMessage();
				reqVideoMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqVideoMsg.setMsgId(Long.valueOf(msgId));
				reqVideoMsg.setMsgType(msgType);
				reqVideoMsg.setFromUserName(fromUserName);
				reqVideoMsg.setToUserName(toUserName);
				reqVideoMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqVideoMsg.setThumbMediaId(ThumbMediaId);
				reqVideoMsg.setMediaId(videoMediaId);
				//weChatMapper.saveReqVideoMsg(reqVideoMsg);
				break;
	
			// 5:地理位置消息
			case WeChatConstant.REQ_MESSAGE_TYPE_LOCATION:
				String Location_X = requestMap.get("Location_X"); // Location_X
																	// 地理位置维度
				String Location_Y = requestMap.get("Location_Y"); // Location_Y
																	// 地理位置精度
				String Scale = requestMap.get("Scale"); // Scale 地图缩放大小
				String Label = requestMap.get("Label"); // Label 地理位置信息
				ReqLocationMessage reqLocationMsg = new ReqLocationMessage();
				reqLocationMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqLocationMsg.setMsgId(Long.valueOf(msgId));
				reqLocationMsg.setMsgType(msgType);
				reqLocationMsg.setFromUserName(fromUserName);
				reqLocationMsg.setToUserName(toUserName);
				reqLocationMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqLocationMsg.setLocation_X(Location_X);
				reqLocationMsg.setLocation_Y(Location_Y);
				reqLocationMsg.setLabel(Label);
				reqLocationMsg.setScale(Scale);
				//weChatMapper.saveReqLocationMsg(reqLocationMsg);
				break;
	
			// 6:链接消息
			case WeChatConstant.REQ_MESSAGE_TYPE_LINK:
				String Title = requestMap.get("Title"); // 消息标题
				String Description = requestMap.get("Description"); // 消息描述
				String Url = requestMap.get("Url"); // 消息链接
				ReqLinkMessage reqLinkMsg = new ReqLinkMessage();
				reqLinkMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqLinkMsg.setMsgId(Long.valueOf(msgId));
				reqLinkMsg.setMsgType(msgType);
				reqLinkMsg.setFromUserName(fromUserName);
				reqLinkMsg.setToUserName(toUserName);
				reqLinkMsg.setCreateTime(Long.valueOf(msgCreateTime));
				reqLinkMsg.setTitle(Title);
				reqLinkMsg.setDescription(Description);
				reqLinkMsg.setUrl(Url);
				//weChatMapper.saveReqLinkMsg(reqLinkMsg);
				break;
			default:
				break;
		}
	}
	
	// 最新活动
	private ResBaseMessage myBook(String openID,String fromUserName){
		NewsMessage news=new NewsMessage();
		news.setToUserName(openID);
		news.setFromUserName(fromUserName);
		news.setCreateTime(new Date().getTime());
		news.setFuncFlag(0);
		news.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);	
		List<Article> arts=new ArrayList<Article>();
		
		Article art0=new Article();
		art0.setTitle("我的借阅信息 ");
		art0.setDescription("借阅信息查询");		
		art0.setPicUrl("https://mmbiz.qlogo.cn/mmbiz/e4o9hIVG5qkRPuJfia1nyJo3ia2AFPRQmSy9aZu6FG471bic23GklTJ81Fg9OCOMENNbFerCMUpETh621LUtqGUrg/0?wx_fmt=png");
		art0.setUrl("http://115.29.169.76/bbs//book/mybook.htm?openid="+openID);
		arts.add(art0);
		
		news.setArticleCount(arts.size());
		news.setArticles(arts);
		return news;
	}
	
	
	/**
	 * 自定义菜单点击事件
	 * @param requestMap
	 * @param resMessage
	 */
	private ResBaseMessage processMenuClick(Map<String, String> requestMap,String ip){
		ResBaseMessage responseMsg=new ResBaseMessage();
		String openID=requestMap.get("FromUserName");         
		String fromUserName=requestMap.get("ToUserName");
		String eventKey = requestMap.get("EventKey");
		switch(eventKey){
			// 我的借阅信息	
			case "3": 
				responseMsg=myBook(openID,fromUserName);
				break;
			default:break;
		}
		return responseMsg;
	}
	
}
